package codec

import (
	"encoding/json"
	"io"

	"gitee.com/zwczou/lnet"
)

type JsonProtocol struct {
}

func Json() *JsonProtocol {
	return &JsonProtocol{}
}

func (j *JsonProtocol) NewCodec(rw io.ReadWriter) (lnet.Codec, error) {
	codec := &jsonCodec{
		p:       j,
		encoder: json.NewEncoder(rw),
		decoder: json.NewDecoder(rw),
	}
	codec.closer, _ = rw.(io.Closer)
	return codec, nil
}

type jsonCodec struct {
	p       *JsonProtocol
	closer  io.Closer
	encoder *json.Encoder
	decoder *json.Decoder
}

func (c *jsonCodec) Receive(msg interface{}) error {
	return c.decoder.Decode(&msg)
}

func (c *jsonCodec) Send(msg interface{}) error {
	return c.encoder.Encode(&msg)
}

func (c *jsonCodec) Close() error {
	if c.closer != nil {
		return c.closer.Close()
	}
	return nil
}
